<template>
	<xn-form-container
		:title="formState.id ? '编辑职位' : '新增职位'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formState" :rules="formRules">
			<a-form-item label="招聘城市" name="city">
				<a-select v-model:value="formState.city" placeholder="请选择招聘城市" :options="branchCityOptions" />
			</a-form-item>
			<a-form-item label="职位名称" name="name">
				<a-input v-model:value="formState.name" placeholder="请输入职位名称" />
			</a-form-item>
			<a-form-item label="职位状态" name="status">
				<a-switch
					:checked="formState.status === 'ENABLE'"
					@change="(checked) => (formState.status = checked ? 'ENABLE' : 'DISABLED')"
					checked-children="启用"
					un-checked-children="停用"
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { reactive, ref } from 'vue'
	import recruitmentPositionApi from '@/api/hrms/recruitment/positions/recruitmentPositionsApi'
	import tool from '@/utils/tool'
	import { message } from 'ant-design-vue'

	const emit = defineEmits(['successful'])
	const visible = ref(false)
	const submitLoading = ref(false)
	const formRef = ref()
	const branchCityOptions = tool.dictList('BRANCH_CITY')

	// 表单数据
	const formState = reactive({
		id: undefined,
		city: undefined,
		name: undefined,
		status: 'ENABLE'
	})

	// 表单验证规则
	const formRules = {
		city: [{ required: true, message: '请选择招聘城市' }],
		name: [{ required: true, message: '请输入职位名称' }]
	}

	// 打开表单
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			// 如果是编辑状态，确保状态值正确设置
			Object.assign(formState, record, {
				status: record.status || 'ENABLE'
			})
		} else {
			// 新增时设置默认值
			resetForm()
		}
	}

	// 关闭表单
	const onClose = () => {
		visible.value = false
		resetForm()
	}

	// 重置表单
	const resetForm = () => {
		Object.assign(formState, {
			id: undefined,
			city: undefined,
			name: undefined,
			status: 'ENABLE' // 默认启用
		})
		formRef.value?.resetFields()
	}

	// 提交表单
	const onSubmit = async () => {
		if (submitLoading.value) return
		try {
			await formRef.value.validateFields()
			submitLoading.value = true
			await recruitmentPositionApi.insertOrEdit(formState)
			onClose()
			emit('successful')
		} catch (error) {
			console.error('提交失败:', error)
			message.error(error.message || '操作失败')
		} finally {
			submitLoading.value = false
		}
	}

	// 暴露方法给父组件
	defineExpose({
		onOpen,
		onClose
	})
</script>
